package com.ys.service.overseas.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.entity.overseas.TosChannelStock;
import com.ys.entity.sys.YsCol;
import com.ys.mapper.overseas.OverseasMapper;
import com.ys.mapper.overseas.TosChannelStockMapper;
import com.ys.service.overseas.TosChannelStockService;
import com.ys.util.CheckUtil;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * HW商品渠道库存
 */
@Service("tosChannelStockService")
public class TosChannelStockServiceImpl implements TosChannelStockService {
	private static final Logger logger = LoggerFactory.getLogger(TosChannelStockServiceImpl.class);

	@Autowired
	private TosChannelStockMapper tosChannelStockMapper;

	@Autowired
	private OverseasMapper overseasMapper;

	@Autowired
	private CheckUtil checkUtil;



	/**
	 * 参数验证
	 */
	public String checkParams(Map<String, Object> params, Long menuId) throws Exception {
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		//验证必填字段的非空；其他字段的长度限制、类型
		String backMsg = checkUtil.checkTableColLengthAndDataType("TOS_ChannelStock",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);

		return backMsg;
	}

	/**
	 * 批量导入
	 */
	@Override
	public R importInfo(String rows, Long menuId){
		logger.info("HW商品渠道库存导入的数据：\n"+rows);
		try {
			//获取所有的精品库信息
			List<Map<String,Object>> oldList = new TosChannelStock()
					.addLeftJoin("TOS_ProductBasis B ON A.ProductCode = B.Code ")//HW商品表
					.addField("B.SignCode AS signCode")//标识编码

					.addLeftJoin("TOS_PlatformInformation C ON C.Id = B.PlatformId ")//平台信息维护表
					.addField("C.HwChannel AS hwChannel")//渠道

					.queryMap();
			StringBuilder errorMsg = new StringBuilder();

			//获取导入数据
			JSONArray detailList = JSON.parseArray(rows);
			for(int i=0;i<detailList.size();i++){
				JSONObject info = detailList.getJSONObject(i);
				//Map infoMap = JSONObject.parseObject(info.toString(), Map.class);
				Map<String, Object> infoMap = new HashMap<>();
				for (String key : info.keySet()) {
					infoMap.put(key, info.get(key)!=null?info.get(key).toString().trim():info.get(key));
				}


				//验证导入字段

				String backMsg = checkParams(infoMap, menuId);
				if(backMsg!=null && !"".equals(backMsg)){//若有误，则跳过这条信息
					logger.error("第"+(i+1)+"条数据导入有误：\n"+backMsg);
					errorMsg.append("第"+(i+1)+"条数据导入有误：\n"+backMsg);
					//return R.error("第"+(i+1)+"条数据导入有误：\n"+backMsg);
					continue;
				}
				//验证标识编码
				if(info.get("signCode")==null || "".equals(info.get("signCode"))){
					logger.error("第"+(i+1)+"条数据标识编码为空");
					errorMsg.append("第"+(i+1)+"条数据标识编码为空\n");
					continue;
				}

				//验证渠道
				if(info.get("hwChannel")==null || "".equals(info.get("hwChannel"))){
					logger.error("第"+(i+1)+"条数据渠道为空");
					errorMsg.append("第"+(i+1)+"条数据渠道为空\n");
					continue;
				}
				List<Map<String,Object>> oldListByCode = oldList.stream()
						.filter(item->item.get("signCode").toString().equals(info.get("signCode").toString())
								&& item.get("hwChannel").toString().equals(info.get("hwChannel").toString()))
						.collect(Collectors.toList());
				if(oldListByCode.size()<=0){
					logger.error("标识编码："+info.get("signCode")+"、渠道："+info.get("hwChannel")+"不存在");
					errorMsg.append("标识编码："+info.get("signCode")+"、渠道："+info.get("hwChannel")+"不存在");
					continue;
				}
				if(checkUtil.isNotNullByObject(infoMap.get("purchaseCostAmount")) ){
					infoMap.put("purchaseCostAmount",infoMap.get("purchaseCostAmount").toString().trim());
				}
				if(checkUtil.isNotNullByObject(infoMap.get("deliveryCostAmount")) ){
					infoMap.put("deliveryCostAmount",infoMap.get("deliveryCostAmount").toString().trim());
				}
				if(checkUtil.isNotNullByObject(infoMap.get("stockNum")) ){
					infoMap.put("stockNum",infoMap.get("stockNum").toString().trim());
				}
				infoMap.put("id",oldListByCode.get(0).get("id"));
				TosChannelStock updateDate = JSON.parseObject(JSON.toJSONString(infoMap), TosChannelStock.class);
				//编辑
				tosChannelStockMapper.update(updateDate);
			}

			if(errorMsg.length()>0){
				return R.error(errorMsg.toString());
			}


		}catch (Exception e){
			logger.error("导入出错：",e.getMessage(),e);
			return R.error("导入出错,请稍后重试!");
		}


		return R.ok("导入成功！");
	}





}
